<template>
  <div class="banner-list-container">
    <h2 class="page-title">轮播图管理</h2>
    
    <!-- 操作栏 -->
    <el-card shadow="never" class="toolbar-card">
      <el-row :gutter="20">
        <el-col :span="18">
          <el-space wrap>
            <el-button type="primary" icon="Plus" @click="handleCreate">
              新增轮播图
            </el-button>
            <el-button icon="Refresh" @click="loadBannerList">刷新</el-button>
          </el-space>
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="searchQuery"
            placeholder="搜索标题"
            clearable
            @clear="loadBannerList"
            @keyup.enter="loadBannerList"
          >
            <template #append>
              <el-button icon="Search" @click="loadBannerList" />
            </template>
          </el-input>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 轮播图列表 -->
    <el-card shadow="never" class="table-card">
      <el-table
        v-loading="loading"
        :data="bannerList"
        stripe
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" />
        
        <el-table-column prop="imageUrl" label="图片" width="150">
          <template #default="{ row }">
            <el-image
              :src="row.imageUrl"
              fit="cover"
              class="banner-image"
              :preview-src-list="[row.imageUrl]"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="title" label="标题" min-width="150" />
        
        <el-table-column prop="subtitle" label="副标题" min-width="150" show-overflow-tooltip />
        
        <el-table-column prop="bannerType" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getBannerTypeColor(row.bannerType)" size="small">
              {{ getBannerTypeText(row.bannerType) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="sortOrder" label="排序" width="80" />
        
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="startTime" label="开始时间" width="180" />
        
        <el-table-column prop="endTime" label="结束时间" width="180" />
        
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              link
              icon="Edit"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              icon="Delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadBannerList"
          @current-change="loadBannerList"
        />
      </div>
    </el-card>
    
    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="bannerFormRef"
        :model="bannerForm"
        :rules="bannerRules"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="bannerForm.title" placeholder="请输入标题" />
        </el-form-item>
        
        <el-form-item label="副标题" prop="subtitle">
          <el-input v-model="bannerForm.subtitle" placeholder="请输入副标题" />
        </el-form-item>
        
        <el-form-item label="轮播图" prop="imageUrl">
          <el-upload
            class="banner-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="handleBeforeUpload"
            :http-request="handleUpload"
          >
            <img v-if="bannerForm.imageUrl" :src="bannerForm.imageUrl" class="banner-preview" />
            <el-icon v-else class="banner-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸：750x400px</div>
        </el-form-item>
        
        <el-form-item label="类型" prop="bannerType">
          <el-radio-group v-model="bannerForm.bannerType">
            <el-radio :label="1">活动</el-radio>
            <el-radio :label="2">课程</el-radio>
            <el-radio :label="3">成功案例</el-radio>
            <el-radio :label="4">外部链接</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item
          v-if="bannerForm.bannerType !== 4"
          label="关联ID"
          prop="targetId"
        >
          <el-input-number
            v-model="bannerForm.targetId"
            :min="1"
            placeholder="请输入关联ID"
          />
        </el-form-item>
        
        <el-form-item
          v-if="bannerForm.bannerType === 4"
          label="跳转链接"
          prop="linkUrl"
        >
          <el-input v-model="bannerForm.linkUrl" placeholder="请输入跳转链接" />
        </el-form-item>
        
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="bannerForm.sortOrder" :min="0" />
          <div class="form-tip">数字越小越靠前</div>
        </el-form-item>
        
        <el-form-item label="展示时间">
          <el-date-picker
            v-model="timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="bannerForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { API_ENDPOINTS } from '@/config/api'

const loading = ref(false)
const submitLoading = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const bannerList = ref([])

const dialogVisible = ref(false)
const dialogTitle = ref('新增轮播图')
const bannerFormRef = ref(null)
const timeRange = ref([])

const bannerForm = reactive({
  bannerId: null,
  title: '',
  subtitle: '',
  imageUrl: '',
  bannerType: 1,
  targetId: null,
  linkUrl: '',
  sortOrder: 0,
  status: 1,
  startTime: null,
  endTime: null
})

const bannerRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  imageUrl: [{ required: true, message: '请上传轮播图', trigger: 'change' }],
  bannerType: [{ required: true, message: '请选择类型', trigger: 'change' }],
  targetId: [{ required: true, message: '请输入关联ID', trigger: 'blur' }],
  linkUrl: [{ required: true, message: '请输入跳转链接', trigger: 'blur' }]
}

// 加载轮播图列表
const loadBannerList = async () => {
  loading.value = true
  try {
    const response = await request.get(API_ENDPOINTS.BANNER_LIST, {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        keyword: searchQuery.value
      }
    })
    
    if (response.code === 200) {
      // MyBatis-Plus的Page对象使用records字段
      bannerList.value = response.data.records || []
      total.value = response.data.total || 0
    }
  } catch (error) {
    console.error('加载轮播图列表失败:', error)
    ElMessage.error('加载轮播图列表失败')
  } finally {
    loading.value = false
  }
}

// 获取类型文本
const getBannerTypeText = (type) => {
  const types = { 1: '活动', 2: '课程', 3: '成功案例', 4: '外部链接' }
  return types[type] || '未知'
}

// 获取类型颜色
const getBannerTypeColor = (type) => {
  const colors = { 1: 'success', 2: 'primary', 3: 'warning', 4: 'info' }
  return colors[type] || ''
}

// 新增
const handleCreate = () => {
  dialogTitle.value = '新增轮播图'
  Object.assign(bannerForm, {
    bannerId: null,
    title: '',
    subtitle: '',
    imageUrl: '',
    bannerType: 1,
    targetId: null,
    linkUrl: '',
    sortOrder: 0,
    status: 1,
    startTime: null,
    endTime: null
  })
  timeRange.value = []
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑轮播图'
  Object.assign(bannerForm, row)
  timeRange.value = row.startTime && row.endTime ? [row.startTime, row.endTime] : []
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个轮播图吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await request.delete(`${API_ENDPOINTS.BANNER_DELETE}/${row.bannerId}`)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadBannerList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

// 状态切换
const handleStatusChange = async (row) => {
  try {
    const response = await request.put(`${API_ENDPOINTS.BANNER_UPDATE}/${row.bannerId}`, {
      status: row.status
    })
    
    if (response.code === 200) {
      ElMessage.success('状态更新成功')
    } else {
      row.status = row.status === 1 ? 0 : 1
    }
  } catch (error) {
    console.error('状态更新失败:', error)
    row.status = row.status === 1 ? 0 : 1
  }
}

// 上传前检查
const handleBeforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB')
    return false
  }
  return true
}

// 上传图片
const handleUpload = async (options) => {
  const formData = new FormData()
  formData.append('file', options.file)
  
  try {
    const response = await request.post(API_ENDPOINTS.UPLOAD_IMAGE, formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    
    if (response.code === 200) {
      bannerForm.imageUrl = response.data.url || response.data
      ElMessage.success('上传成功')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!bannerFormRef.value) return
  
  try {
    await bannerFormRef.value.validate()
    
    if (timeRange.value && timeRange.value.length === 2) {
      bannerForm.startTime = timeRange.value[0]
      bannerForm.endTime = timeRange.value[1]
    }
    
    submitLoading.value = true
    
    const url = bannerForm.bannerId
      ? `${API_ENDPOINTS.BANNER_UPDATE}/${bannerForm.bannerId}`
      : API_ENDPOINTS.BANNER_CREATE
    const method = bannerForm.bannerId ? 'put' : 'post'
    
    const response = await request[method](url, bannerForm)
    
    if (response.code === 200) {
      ElMessage.success(bannerForm.bannerId ? '更新成功' : '创建成功')
      dialogVisible.value = false
      loadBannerList()
    }
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

onMounted(() => {
  loadBannerList()
})
</script>

<style scoped>
.banner-list-container {
  padding: 0;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0 0 20px 0;
}

.toolbar-card {
  margin-bottom: 20px;
}

.table-card {
  margin-top: 20px;
}

.banner-image {
  width: 120px;
  height: 64px;
  border-radius: 4px;
  cursor: pointer;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.banner-uploader {
  display: inline-block;
}

.banner-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  width: 360px;
  height: 192px;
}

.banner-uploader :deep(.el-upload:hover) {
  border-color: #409EFF;
}

.banner-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 360px;
  height: 192px;
  text-align: center;
  line-height: 192px;
}

.banner-preview {
  width: 360px;
  height: 192px;
  object-fit: cover;
}

.upload-tip,
.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}
</style>

